package com.ruoyi.central.controller;

import java.io.Serializable;
import java.util.*;

import com.ruoyi.central.domain.TopCentralProductRelation;
import com.ruoyi.central.service.ITopCentralProductMaterialTypeService;
import com.ruoyi.central.service.ITopCentralProductRelationService;
import com.ruoyi.common.utils.CollectionUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.service.ServiceUtils;
import com.ruoyi.common.validation.group.InsertGroup;
import com.ruoyi.common.validation.group.UpdateGroup;
import org.apache.poi.util.StringUtil;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import com.ruoyi.common.utils.bean.SelectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.central.domain.TopCentralProductType;
import com.ruoyi.central.service.ITopCentralProductTypeService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import org.springframework.validation.annotation.Validated;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.validation.group.UpdateBatchGroup;
import com.ruoyi.common.core.domain.StateVo;

import java.util.stream.Collectors;

/**
 * 产品类型Controller
 * 
 * @author ruoyi
 * @date 2022-03-02
 */
@Controller
@RequestMapping("/central/centralProductType")
public class TopCentralProductTypeController extends BaseController
{
    private String prefix = "central/centralProductType";

    @Autowired
    private ITopCentralProductTypeService topCentralProductTypeService;

    @Autowired
    private ITopCentralProductMaterialTypeService productMaterialTypeService;

    @Autowired
    private ITopCentralProductRelationService productRelationService;

    @RequiresPermissions("central:centralProductType:view")
    @GetMapping()
    public String centralProductType()
    {
        return prefix + "/centralProductType";
    }

    /**
     * 根据当前物料类型编号获取它的父物料类型集合
     * @param materialTypeId 物料类型编号
     * @return
     */
    @GetMapping("/getParentMaterialTypeList/{materialTypeId}")
    @ResponseBody
    public AjaxResult getParentMaterialTypeList(@PathVariable("materialTypeId")Integer materialTypeId){

        Set<Integer> parentMaterialTypeIds = productRelationService.selectAllMap()
                .values().stream().filter(materialRelation -> materialRelation.getProductPartTypeId().equals(materialTypeId))
                .map(TopCentralProductRelation::getProductTypeId).collect(Collectors.toSet());

        if(StringUtils.isNotEmpty(parentMaterialTypeIds)){

            List<TopCentralProductType> parentMaterialTypeList = new ArrayList(parentMaterialTypeIds.size());

            Map<? extends Serializable, TopCentralProductType> materialTypeMap = topCentralProductTypeService.selectAllMap();
            parentMaterialTypeIds.stream().filter(materialTypeMap::containsKey).
                    forEach(parentMaterialTypeId->parentMaterialTypeList.add(materialTypeMap.get(parentMaterialTypeId)));

            return AjaxResult.success(parentMaterialTypeList);
        }

        return AjaxResult.success(CollectionUtils.EMPTY_LIST);
    }

    /**
     * 查询产品类型列表
     */
    @RequiresPermissions("central:centralProductType:list")
    @GetMapping("/list")
    @ResponseBody
    public TableDataInfo list(TopCentralProductType topCentralProductType)
    {
        startPage();
        List<TopCentralProductType> list = topCentralProductTypeService.selectList(topCentralProductType);

        ServiceUtils.complete(list,productMaterialTypeService,(productMaterialTypeMap,item)->item.setProductMaterialType(productMaterialTypeMap.get(item.getProductMaterialTypeId())));

        return getDataTable(list);
    }

    /**
     * 查询简单的产品类型列表 用于select选择器
     */
    @GetMapping("/simpleList")
    @ResponseBody
    public AjaxResult simpleList(TopCentralProductType topCentralProductType){

        Integer productMaterialTypeId = topCentralProductType.getProductMaterialTypeId();

        Collection<TopCentralProductType> topCentralProductTypeList = topCentralProductTypeService.selectAllMap().values();

        if(StringUtils.isNotNull(productMaterialTypeId)){
            topCentralProductTypeList = topCentralProductTypeList.stream().filter(item->productMaterialTypeId.equals(item.getProductMaterialTypeId())).collect(Collectors.toList());
        }

        return AjaxResult.success(SelectUtils.buildSelectList(topCentralProductTypeList,TopCentralProductType::getId,TopCentralProductType::getName,true));
    }

    /**
     * 获取产品类型详细信息
     */
    @RequiresPermissions("central:centralProductType:query")
    @GetMapping(value = "/{id}")
    @ResponseBody
    public AjaxResult getInfo(@PathVariable("id") Integer id)
    {
        return AjaxResult.success(topCentralProductTypeService.selectById(id));
    }

    /**
     * 获取自增排序值
     * @param topCentralProductType 过滤条件
     * @return
     */
    @GetMapping("/getIncrementWeight")
    @ResponseBody
    public AjaxResult getIncrementWeight(TopCentralProductType topCentralProductType){
        int weigth = topCentralProductTypeService.getMaxOfWeight(topCentralProductType);
        return AjaxResult.success(++weigth);
    }

    /**
     * 下载产品类型导入模板
     */
    @GetMapping("/importTemplate")
    @ResponseBody
    public void importTemplate(HttpServletResponse response)
    {
        ExcelUtil<TopCentralProductType> util = new ExcelUtil<>(TopCentralProductType.class);
        util.importTemplateExcel(response, "产品类型数据");
    }

    /**
     * 导入产品类型数据
     * @param file 产品类型数据文件
     * @param updateSupport 是否为更新
     */
    @Log(title = "产品类型", businessType = BusinessType.IMPORT)
    @RequiresPermissions("central:centralProductType:import")
    @PostMapping("/importData")
    @ResponseBody
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception
    {
        ExcelUtil<TopCentralProductType> util = new ExcelUtil<>(TopCentralProductType.class);
        List<TopCentralProductType> topCentralProductTypeList = util.importExcel(file.getInputStream());

        if(updateSupport){
            if(topCentralProductTypeService.updateBatchById(topCentralProductTypeList)){
                return AjaxResult.success("导入产品类型数据覆盖成功！");
            }
            return AjaxResult.error("导入产品类型数据覆盖失败！");
        }
        if(topCentralProductTypeService.insertBatch(topCentralProductTypeList)){
            return AjaxResult.success("导入产品类型数据新增成功！");
        }
        return AjaxResult.error("导入产品类型数据新增失败！");
    }

    /**
     * 导出产品类型列表
     */
    @RequiresPermissions("central:centralProductType:export")
    @Log(title = "产品类型", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(TopCentralProductType topCentralProductType)
    {
        List<TopCentralProductType> list = topCentralProductTypeService.selectList(topCentralProductType);
        ExcelUtil<TopCentralProductType> util = new ExcelUtil<TopCentralProductType>(TopCentralProductType.class);
        return util.exportExcel(list, "产品类型数据");
    }

    /**
     * 新增产品类型
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存产品类型
     */
    @RequiresPermissions("central:centralProductType:add")
    @Log(title = "产品类型", businessType = BusinessType.INSERT)
    @PostMapping
    @ResponseBody
    public AjaxResult addSave(@Validated(InsertGroup.class) @RequestBody TopCentralProductType topCentralProductType)
    {
        return toAjax(topCentralProductTypeService.insert(topCentralProductType));
    }

    /**
     * 修改产品类型
     */
    @RequiresPermissions("central:centralProductType:edit")
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Integer id, ModelMap mmap)
    {
        TopCentralProductType topCentralProductType = topCentralProductTypeService.selectById(id);
        mmap.put("topCentralProductType", topCentralProductType);
        return prefix + "/edit";
    }

    /**
     * 修改保存产品类型
     */
    @RequiresPermissions("central:centralProductType:edit")
    @Log(title = "产品类型", businessType = BusinessType.UPDATE)
    @PutMapping
    @ResponseBody
    public AjaxResult editSave(@Validated(UpdateGroup.class) @RequestBody TopCentralProductType topCentralProductType)
    {
        return toAjax(topCentralProductTypeService.updateById(topCentralProductType));
    }

    /**
     * 修改产品类型 状态 根据 ids 主键
     */
    @RequiresPermissions("central:centralProductType:edit")
    @Log(title = "产品类型", businessType = BusinessType.UPDATE)
    @PutMapping("/updateStateByIds")
    @ResponseBody
    public AjaxResult updateStateByIds(@Validated(value= UpdateBatchGroup.class)@RequestBody StateVo<Integer> stateVo)
    {
        return toAjax(topCentralProductTypeService.updateStateByIds(stateVo.getIds(),stateVo.getState()));
    }

    /**
     * 删除产品类型
     */
    @RequiresPermissions("central:centralProductType:remove")
    @Log(title = "产品类型", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    @ResponseBody
    public AjaxResult deleteByIds(@PathVariable("ids") List<Integer> ids)
    {
            return toAjax(topCentralProductTypeService.deleteByIds(ids));
    }
}
